package com.songlanyun.modules.rabbitmq.mq.consumer;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.rabbitmq.client.Channel;
import com.songlanyun.common.enums.MemberConstant;
import com.songlanyun.common.utils.custom.ClassConvertUtils;
import com.songlanyun.modules.account.entity.AccountEntity;
import com.songlanyun.modules.account.model.vo.AccountParentVO;
import com.songlanyun.modules.account.service.AccountService;
import com.songlanyun.modules.config.dao.YxtTeamRewardConfigDao;
import com.songlanyun.modules.config.dao.YxtUserTeamRateConfigDao;
import com.songlanyun.modules.config.entity.YxtUserTeamRateConfig;
import com.songlanyun.modules.config.model.PointGradeConfigDTO;
import com.songlanyun.modules.config.service.PointGradeConfigService;
import com.songlanyun.modules.order.entity.Order;
import com.songlanyun.modules.order.service.ChildOrderService;
import com.songlanyun.modules.order.service.OrderService;
import com.songlanyun.modules.rabbitmq.MqConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.BufferedWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 会员升级
 */
@Component
@Slf4j
public class UserUpgradeConsumer extends BaseConsumer {


    @Autowired
    private AccountService accountService;

    @Autowired
    private PointGradeConfigService pointGradeConfigService;

    @Autowired
    private ChildOrderService childOrderService;

    @Autowired
    private YxtUserTeamRateConfigDao yxtUserTeamRateConfig;


    @Override
    protected void process(Message message) {
        Long userId = ClassConvertUtils.objToLong(new String(message.getBody()));

        AccountEntity account = accountService.getUserById(userId, true);
        account.setActivating(true);
        account.setLastActivatingTime(new Date());
        accountService.modify(account);
        System.out.println("开始升级判断操作");
        Path path = Paths.get("/opt/gradelog/autogradelog.txt");//追加写模式
//        Path path = Paths.get("C:\\Users\\Administrator\\Desktop\\app.log");//追加写模式
        try (BufferedWriter writer =
                     Files.newBufferedWriter(path,
                             StandardCharsets.UTF_8,
                             StandardOpenOption.APPEND)){
            writer.write("用户id="+account.getId()+"时间="+new Date()+System.lineSeparator());
        }catch (Exception e){

        }

        //查询当前用户所有上级用户
        List<AccountParentVO> allParentUser = accountService.getAllLevelUpParentUser(userId);
        if(CollectionUtil.isEmpty(allParentUser)) {
            return ;
        }
        System.out.println("上级用户="+allParentUser);
        //团队奖励配置
        List<YxtUserTeamRateConfig> teamConfig = yxtUserTeamRateConfig.selectList
                (new LambdaQueryWrapper<YxtUserTeamRateConfig>().eq(YxtUserTeamRateConfig::getType,"team").orderByAsc(YxtUserTeamRateConfig::getId));

        List<YxtUserTeamRateConfig> config = yxtUserTeamRateConfig.selectList
                (new LambdaQueryWrapper<YxtUserTeamRateConfig>().orderByAsc(YxtUserTeamRateConfig::getId));
        //将团队配置按等级排序
        System.out.println("团队配置="+teamConfig);
        List<YxtUserTeamRateConfig> teamRateConfig = this.getListTeamConfig(teamConfig);
        List<YxtUserTeamRateConfig> allRateConfig = this.getListTeamConfig(config);

        System.out.println("团队奖励配置="+teamRateConfig);
//        PointGradeConfigDTO config = pointGradeConfigService.info();

        for (AccountParentVO parent:allParentUser) {
            System.out.println("当前用户id"+parent.getId());
            //当前用户下一等级所需的条件
            if(teamRateConfig.size() < parent.getTeamGrade()+1){
                continue;
            }
            //当前用户的升级条件数据
            YxtUserTeamRateConfig thisUserLevelNeed = teamRateConfig.get(parent.getTeamGrade()+1);
            if(thisUserLevelNeed.getNeedInvite() > 0 || thisUserLevelNeed.getNeedUseAmount() > 0){
                System.out.println("进入直推和业绩判断");
                //当前用户有效直推人数
                Integer childActivatingCount = accountService.getChildActivatingCount(parent.getId());
                System.out.println("当前用户有效直推人数="+childActivatingCount);
                System.out.println("当前用户个人业绩="+parent.getPersonalPerformance());
                System.out.println("当前童虎升级需求"+thisUserLevelNeed);
                //直推或者个人业绩需求升级
                if(parent.getPersonalPerformance().compareTo(BigDecimal.valueOf(thisUserLevelNeed.getNeedUseAmount())) < 0
                        && childActivatingCount < thisUserLevelNeed.getNeedInvite()){
                    continue;
                }
                System.out.println("当前用户升级成功,userId:"+parent.getId());
                AccountEntity entity = accountService.getUserById(parent.getId(), false);
                if(ObjectUtil.isNotNull(entity)) {
                    //满足一个条件就升级
                    entity.setTeamGrade(Math.toIntExact(thisUserLevelNeed.getId()));
                    accountService.modify(entity);
                    continue;
                }
            }else{
                System.out.println("进入团队业绩判断");
                //小区团队业绩需求升级
                //当前用户小区
                BigDecimal thisTeamAmount = BigDecimal.valueOf(0);

                List<AccountEntity> inviteUser = accountService.getUserInviteList(parent.getId());
                System.out.println("直推的用户:"+inviteUser);
                if(inviteUser.isEmpty()){
                    continue;
                }
                for(int i = 0; i<= inviteUser.size()-1; i++) {
                        thisTeamAmount = thisTeamAmount.add(inviteUser.get(i).getTeamPerformance());
                }
                System.out.println("当前用户下的小区业绩:"+thisTeamAmount);
                System.out.println("当前升级需求数据"+thisUserLevelNeed);
                if(thisTeamAmount.compareTo(BigDecimal.valueOf(0)) < 1){
                    continue;
                }
                //满足业绩条件后升级
                if(thisTeamAmount.compareTo(BigDecimal.valueOf(thisUserLevelNeed.getNeedTeamAmount())) >= 0 ){
                    AccountEntity entity = accountService.getUserById(parent.getId(), false);
                    System.out.println("当前用户升级成功,userIds:"+parent.getId());
                    if(ObjectUtil.isNotNull(entity)) {
                        //满足一个条件就升级
                        entity.setTeamGrade(Math.toIntExact(thisUserLevelNeed.getId()));
                        accountService.modify(entity);
                        continue;
                    }
                }
            }


        }

        for (AccountParentVO parent:allParentUser) {
            //董事升级
            //获取当前用户董事等级
            System.out.println("进入董事升级================");
            Integer directorGrade = parent.getDirectorGrade();
            //如果不是最后一级，代表还可以升级
            if (directorGrade != 10){
                System.out.println("当前董事级别"+directorGrade);
                //如果是没有董事等级
                if (directorGrade == 0){
                    System.out.println("当前没有董事等级");
                    //下一个等级需要的人数
                    Integer managerNeedNum = allRateConfig.get(8).getManagerNeedNum();
                    //升级下一个董事需要的等级人
                    Integer managerNeedLevel = allRateConfig.get(8).getManagerNeedLevel();
                    int count = accountService.count(new LambdaQueryWrapper<AccountEntity>()
                            .like(AccountEntity::getParentPath, "," + parent.getId() + ",")
                            .eq(AccountEntity::getTeamGrade, managerNeedLevel)
                    );
                    System.out.println("满足人数======"+count);
                    //满足人数，升级
                    if (count >= managerNeedNum){
                        AccountEntity accountEntity = accountService.getUserById(parent.getId(), true);
                        accountEntity.setDirectorGrade(8);
                        accountService.modify(accountEntity);
                    }
                }else {
                    //下一个等级需要的人数
                    System.out.println("下一个等级需要的人数=====");
                    Integer managerNeedNum = allRateConfig.get(directorGrade + 1).getManagerNeedNum();
                    //升级下一个董事需要的等级人
                    Integer managerNeedLevel = allRateConfig.get(directorGrade + 1).getManagerNeedLevel();
                    int count = accountService.count(new LambdaQueryWrapper<AccountEntity>()
                            .like(AccountEntity::getParentPath, "," + parent.getId() + ",")
                            .eq(AccountEntity::getDirectorGrade, managerNeedLevel)
                    );
                    //满足人数，升级
                    System.out.println("不是第一级董事需要的人数======="+count);
                    if (count >= managerNeedNum){
                        AccountEntity accountEntity = accountService.getUserById(parent.getId(), true);
                        accountEntity.setDirectorGrade(directorGrade + 1);
                        accountService.modify(accountEntity);
                    }
                }
            }

        }
    }

    public List<YxtUserTeamRateConfig> getListTeamConfig(List<YxtUserTeamRateConfig> list){
        List<YxtUserTeamRateConfig> returnList = new ArrayList<>(Collections.nCopies(list.size()+1, null));
        for(int i = 0; i<list.size(); i++){
            returnList.set(Math.toIntExact(list.get(i).getId()), list.get(i));
        }
        return returnList;
    }

    @RabbitListener(queues = MqConstant.UserUpgradeConstant.USER_UPGRADE_QUEUE)
    public void consume(Message message, Channel channel) throws IOException {
        super.handle(message,channel);
    }
}
